﻿<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Security.Principal" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

    void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        string roles = null;
        FormsIdentity identity = null;
        if (Context.Request.IsAuthenticated)
        {
            if (Context.User.Identity.AuthenticationType == "Forms")
            {
                identity = (FormsIdentity)Context.User.Identity;
                roles = identity.Ticket.UserData;
                Context.User = new GenericPrincipal(identity, roles.Split(','));
            }
            else
                throw new ApplicationException("Configure Authentication mode to [Forms] in web.config");
        }
    }
    
    void Session_Start(object sender, EventArgs e)
    {
        StreamReader reader = null;
        StreamWriter writer = null;
        FileStream fileStream = null;

        string filePath = Server.MapPath("~/App_Data/hit-counter/hit.count");

        try
        {
            int count = 0;

            if (!File.Exists(filePath))
            {
                writer = File.CreateText(filePath);
                writer.WriteLine(count++);
                writer.Close();
            }
            reader = File.OpenText(filePath);
            count = Convert.ToInt32(reader.ReadLine());
            count++;
            reader.Close();

            fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
            writer = new StreamWriter(fileStream);
            writer.WriteLine(count);

            writer.Close();
            fileStream.Close();
        }
        catch (Exception ex)
        {
            ExceptionWriter exWriter = new ExceptionWriter(ex);
            exWriter.WriteException();
        }
        finally
        {
            if (reader != null)
                reader.Close();
            if (writer != null)
                writer.Close();
            if (fileStream != null)
                fileStream.Close();
        }
    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }

       
</script>
